# @author: uuz
# encoding = utf-8
from werkzeug.security import generate_password_hash, check_password_hash

from ext import db


class User(db.Model):
    __tablename__ = "user"
    id = db.Column(db.Integer, nullable=False, primary_key=True, autoincrement=True)
    account = db.Column(db.String(20), nullable=False)
    nickname = db.Column(db.String(20), nullable=True)
    realname = db.Column(db.String(5), nullable=False, default="")
    _password = db.Column(db.String(100), nullable=False)
    mobile = db.Column(db.String(11), nullable=True)
    user_img = db.Column(db.Text, nullable=True)

    orders = db.relationship("Order", foreign_keys="Order.user_id", backref="user")

    def __init__(self, account, password, realname, **kwargs):
        self.account = account
        self.password = password
        self.realname = realname
        self.nickname = kwargs.get('nickname')
        self.mobile = kwargs.get('mobile')
        self.user_img = kwargs.get('user_img')

    @property
    def password(self):
        return self._password

    @password.setter
    def password(self, raw_password):
        self._password = generate_password_hash(raw_password)

    def verify_password(self, raw_password):
        result = check_password_hash(self.password, raw_password)
        return result
